package com.zhanghe.study.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

/**
 * @author: zhanghe
 * @date: 2020/6/17 19:43
 */
public class TestNio {
    public static void main(String[] args) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        // 绑定8080端口
        serverSocketChannel.bind(new InetSocketAddress(8080));

        // 注册监听的事件
        // ServerSocketChannel只能注册OP_ACCEPT
        // SocketChannel可注册OP_READ、OP_WRITE、OP_CONNECT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);


        while(true){
            // 询问selector中准备好的事件
            selector.select();
            // 获取到上述询问拿到的事件类型
            Set<SelectionKey> selectionKeys =  selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                if(selectionKey.isAcceptable()){
                    ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
                    // 接收到服务端的请求
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    sc.register(selector,SelectionKey.OP_READ);
                    // 处理过了就要移除掉，否则再次select()还会拿到该事件
                    iterator.remove();
                } else if(selectionKey.isReadable()){
                    SocketChannel sc = (SocketChannel) selectionKey.channel();
                    byteBuffer.clear();
                    int n = sc.read(byteBuffer);
                    if(n > 0){
                        byteBuffer.flip();
                        Charset charset = StandardCharsets.UTF_8;
                        String message = String.valueOf(charset.decode(byteBuffer).array());
                        System.out.println(message);
                    }
                    sc.register(selector,SelectionKey.OP_WRITE);
                    iterator.remove();
                } else if(selectionKey.isWritable()){
                    SocketChannel sc = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    buffer.put("已接收到消息".getBytes());
                    buffer.flip();
                    sc.write(buffer);
                    iterator.remove();
                }
            }
        }

    }
}
